#include<bits/stdc++.h>
using namespace std;
namespace IO{
    const int BUF=1<<21;
    char buff[BUF],*p1=buff,*p2=buff;
    #define getchar() (p1==p2&&(p2=((p1=buff)+fread(buff,1,BUF,stdin)),p1==p2)?EOF:*p1++)
    template<typename T>inline void read(T &x){
        char ch=getchar();x=0;int f=1;
        while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
        while(isdigit(ch)) x=(x<<1)+(x<<3)+(ch^48),ch=getchar();
        x*=f;
    }
}
using namespace IO;
const int N=5005,mod=998244353;
int n,m,a[N],fa1[N],fa2[N];
vector<int> T1[N],T2[N];
int dfn[N],low[N],idx,xl[N],lca[N][N];
void dfs1(int p,int dep){
	xl[dfn[p]=++idx]=p;
	lca[p][p]=dep;
	for(int v:T2[p]){
		dfs1(v,dep+1);
		for(int i=dfn[p];i<dfn[v];++i)
		for(int j=dfn[v];j<=low[v];++j)
			lca[xl[i]][xl[j]]=lca[xl[j]][xl[i]]=dep;
	}
	low[p]=idx;
}
int sz[N],ans,b[N],cnt;
void dfs(int p,int fa){
	sz[p]=1;
	b[++cnt]=p;
	for(int v:T1[p]) if(v^fa) dfs(v,p),sz[p]+=sz[v];
}
int root1,root2;
int main(){
	freopen("tree.in","r",stdin);
	freopen("tree.out","w",stdout); 
	read(n),read(m);
	for(int i=1;i<=n;++i){
		read(fa1[i]);
		if(!fa1[i]) root1=i;
		else T1[fa1[i]].push_back(i),T1[i].push_back(fa1[i]);
	}
	for(int i=1;i<=m;++i){
		read(fa2[i]);
		if(!fa2[i]) root2=i;
		else T2[fa2[i]].push_back(i);
	}
	for(int i=1;i<=n;++i) read(a[i]);
	dfs1(root2,1);
	for(int i=1;i<=n;++i){
		for(int v:T1[i]){
			cnt=0;
			dfs(v,i);
			for(int j=1;j<=cnt;++j)
				if(b[j]<i) ans=(ans+1ll*lca[a[b[j]]][a[i]]*sz[b[j]]%mod*(n-sz[v])%mod)%mod;
		}
	}
	printf("%d\n",ans);
	return 0;
}

